package org.example.springsecurity2.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class SessionController {
    @Autowired
    private SessionRegistry sessionRegistry;

    @GetMapping("/kick")
    public void kick(String username) {
        List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
        for(Object principal : allPrincipals){
            UserDetails userDetails =(UserDetails) principal;
            if(username.equals(userDetails.getUsername())){
                List<SessionInformation> sessions =sessionRegistry.getAllSessions(userDetails,false);
                if(null!=sessions && !sessions.isEmpty()){
                    for (SessionInformation session:sessions){
                        session.expireNow();
                    }
                }
            }
        }
    }
}
